<?php
// +----------------------------------------------------------------------
// | Cron控制器
// +----------------------------------------------------------------------
// | Since: 2014-09-15 16:02
// +----------------------------------------------------------------------
// | Author: shioujun <shioujun@gmail.com>
// +----------------------------------------------------------------------
namespace Crontab\Controller;

use Think\Controller;
use Common\Model\OpenIdModel as OpenId;
use Common\Model\UserModel as User;
use Com\Weixin\WeixinApi;
use Com\Fetch\Fetch;

/**
 */
class TaskController extends Controller
{
    
    /**
     * 更新access token
     */
    function gettoken()
    {
        $wx_obj = new WeixinApi();
        
        $access_token = $wx_obj->getToken( true );
        
        echo $access_token."\n\r";
        var_dump( S('access_token') );
        die;
        
        
        return false;
    }    
    
    /**
     * 更新用户信息
     */
    public function updateWeixinUserInfo()
    {
        $u = new User();
        $userInfo = $u->where(" `nickname` is null or logo is null ")
        ->limit(100)
        ->select();
        $c = 0;
        foreach ($userInfo as $key => $value) {
            if ($c > 10) {
                $c = 0;
                sleep(1);
            }
            $c ++;
            $openid_obj = new OpenId();
            $openid_info = $openid_obj->uid2OpenidInfo($value['id']);
            if( $openid_info && $openid_info['state']==1 ){
                $this->getBasicinfo( $openid_info['openid']  );
            }else{
                echo "Uid:{$value['id']} 的openid没有找到或者state=0\n";
            }
        }
    }
    
    
    private function getBasicinfo($openid)
    {
        $user_obj = new User();
        $info = $user_obj->getWeixinUserDetailInfo($openid);
        
        if( $info ){
            $where = array();
            $where['openid'] = $openid;
            
            $update = $info;
            $rs = $user_obj->where($where)->save($update);
            if( !$rs ){
                echo "更新失败\n\n";
            }
        }else{
            echo "未获得 openid : {$openid} 的信息";
        }
    }

    public function https($url,$data=[]){
        $user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.556.400 QQBrowser/9.0.2524.400";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        if(count($data)>0){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
        curl_setopt ($ch, CURLOPT_COOKIEFILE, dirname(CURR_RUN_FILENAME).'/cookie/cookie.txt');
        curl_setopt ($ch, CURLOPT_COOKIEJAR, dirname(CURR_RUN_FILENAME).'/cookie/cookie.txt');

        $response = curl_exec($ch);

        if($error=curl_error($ch)){
            print_r($error);
        }

        curl_close($ch);
        if(empty($response)){
            echo "empty response : $url \n";
        }
        return $response;

    }

    public function getNovel(){
        $type = [
            1=>'悬疑',
            2=>'历史',
            3=>'军事',
            4=>'玄幻',
            5=>'奇幻',
            6=>'仙侠',
            7=>'武侠',
            8=>'科幻',
            9=>'游戏',
            10=>'同人',
            11=>'都市',
            12=>'言情',
        ];
        foreach ($type as $k=>$v){
            $novels = [];
            $page = 0;
            do{
                $page++;
                $url = "https://m.emeixs.com/Stacks/index/gender/3/type/$k/state/wxbase/click/1/vip/3/p/$page/fromaid/245";
                $fetch = new Fetch();
                $fetch->setContent($this->https($url));
                $result = $fetch->query('.return_hot > li','element');
                $novel = array();
                $page_total = 1;
                $page_str = $fetch->query('.upnextss > b','value')[0];
                if(!empty($page)){
                    $page_total = intval(substr($page_str,strpos($page_str,'/')+1));
                }
                foreach ($result as $item){
                    $tmp_fetch = new Fetch();
                    $tmp_fetch->setContent($item);
                    $tmp['book_name'] = $tmp_fetch->query('h3','value')[0];
                    $tmp['book_info'] = $tmp_fetch->query('p','value')[0];
                    $tmp['book_img'] = $tmp_fetch->query_attr('img','src')[0];
                    $tmp['book_href'] = 'https://m.emeixs.com'.$tmp_fetch->query_attr('a','href')[0];
                    $tmp['book_type'] = $k;
                    if(!empty($tmp['book_name'])){
                        $arr = explode('/',$tmp['book_href']);
                        $tmp['book_id'] = $arr[4];
                        $novel[] = $tmp;
                        $novels[] = $tmp;
                    }
                }
            }while(count($novel)>0 && $page<$page_total);

            if(empty($novels)){
                continue;
            }else{
                M('book')->addAll($novels);
            }
        };

    }

    public function getChapterList(){
        $books = M('book')->where(['book_status'=>0])->limit(0,100)->select();
        if($books){
            foreach ($books as $book){
                $url = "https://m.emeixs.com/Moreinfo/nextchapter/fromaid/245.html";
                $page = 0;
                $bookid = $book['book_id'];
                $chapters = array();
                do{
                    $page++;
                    $data = ['bookid'=>$bookid,'page'=>$page,'paixu'=>'asc'];
                    $fetch = new Fetch();
                    $fetch->setContent($this->https($url,$data));
                    $result = $fetch->query('li','element');
                    if(count($result)>0){
                        foreach ($result as $item){
                            $tmp_fetch = new Fetch();
                            $tmp_fetch->setContent($item);
                            $tmp['ch_name'] = $tmp_fetch->query('span','value')[0];
                            $tmp['is_vip'] = empty($tmp_fetch->query('em','value')[0])?0:1;
                            $tmp['from_source'] = $tmp_fetch->query_attr('a','href')[0];
                            $tmp['book_id'] = $bookid;
                            if(!empty($tmp['ch_name'])){
                                $chapters[] = $tmp;
                            }
                        }
                    }
                }while(count($result)>0);
                $chapter = M('chapter')->where(['book_id'=>$bookid])->find();
                if($chapters && !$chapter){
                    M('chapter')->addAll($chapters);
                    M('book')->where(['book_id'=>$bookid])->setField('book_status',1);
                    echo $bookid." \n";
                }

            }
        }

    }

    protected function updataChapterList($bookid){
        $url = "https://m.emeixs.com/Moreinfo/nextchapter/fromaid/245.html";
        $chapters = array();
        $data = ['bookid'=>$bookid,'page'=>1,'paixu'=>'desc'];
        $fetch = new Fetch();
        $fetch->setContent($this->https($url,$data));
        $result = $fetch->query('li','element');
        if(count($result)>0){
            foreach ($result as $item){
                $tmp_fetch = new Fetch();
                $tmp_fetch->setContent($item);
                $tmp['ch_name'] = $tmp_fetch->query('span','value')[0];
                $tmp['is_vip'] = empty($tmp_fetch->query('em','value')[0])?0:1;
                $tmp['from_source'] = $tmp_fetch->query_attr('a','href')[0];
                $tmp['book_id'] = $bookid;
                if(!empty($tmp['ch_name'])){
                    $chapter = M('chapter')->where(['book_id'=>$bookid,'from_source'=>$tmp['from_source']])->find();
                    if(!$chapter){
                        array_unshift($chapters,$tmp);
                    }else{
                        break;
                    }
                }
            }
        }
        $chapter = M('chapter')->where(['book_id'=>$bookid])->find();
        if($chapter && count($chapters)>0){
            M('chapter')->addAll($chapters);
            echo $bookid." update chapter list \n";
        }
    }

    public function updateNovel(){
        $books = M('book')->where([
            'u_time'=>[
                ['eq','0000-00-00'],['gt',date('Y-m-d',strtotime('-10 days'))],'OR'
            ]
        ])->select();
        if($books){
            foreach ($books as $book){
                $fetch = new Fetch();
                $book_href = str_replace('http:','https:',$book['book_href']);
                $content = $this->https($book_href);
                if($content){
                    $fetch->setContent($content);
                    $result = $fetch->query('p','value');
                    $book_auth = str_replace('作者：','',$result[0]);
                    $u_time = '20'.str_replace('更新：','',$result[3]);
                    M('book')->where(['id'=>$book['id']])->save(['book_auth'=>$book_auth,'u_time'=>$u_time,'book_href'=>$book_href]);
                    echo $book['id']." check \n";
                    $this->updataChapterList($book['id']);
                }else{
                    break;
                }
            }
        }
    }

    public function getChapter(){
        $chapters = M('chapter')->where(['is_vip'=>0])->select();
        foreach ($chapters as $chapter){
            $url = "https://m.emeixs.com/".$chapter['from_source'];
            $fetch = new Fetch();
            $fetch->setContent($this->https($url));
            $content = $fetch->query('.article-content','element')[0];
            if($content){
                M('chapter')->where(['id'=>$chapter['id']])->save(['ch_content'=>$content,'is_vip'=>2]);
                echo $chapter['id']." \n";
            }
        }
    }

    public function getNovelByUrl(){
        $fetch = new Fetch();
        $book_href = "https://m.emeixs.com/Books/1710/fromaid/245.html";
        $content = $this->https($book_href);
        if($content){
            $fetch->setContent($content);
            $result = $fetch->query('p','value');
            $book_auth = str_replace('作者：','',$result[0]);
            $u_time = '20'.str_replace('更新：','',$result[3]);
            $book_name = $fetch->query('h2','value')[0];
            $book_img = $fetch->query_attr('img','src')[0];
            $book_info = $fetch->query('.con_con','value')[0];
            $arr = explode('/',$book_href);
            $book_id = $arr[4];
            $book = [
                'book_id'=>$book_id,
                'book_name'=>$book_name,
                'book_auth'=>$book_auth,
                'u_time'=>$u_time,
                'book_img'=>$book_img,
                'book_info'=>$book_info,
                'book_href'=>$book_href,
                'book_type'=>'0',
                'book_status'=>'0',
            ];
            $b = M('book')->where(['book_id'=>$book_id])->find();
            if(!$b){
                $bool = M('book')->data($book)->add();
                if($bool){
                    $this->getChapterList();
                    $this->getChapter();
                }
            }
        }
    }
}